package com.example.test.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.zip.Inflater;














import com.ant.liao.GifView;
import com.example.test.R;
import com.example.test.R.id;
import com.example.test.R.layout;
import com.example.test.model.CommonFunc;
import com.example.test.model.Constants;
import com.example.test.model.FormatTools;
import com.example.test.model.StatusTextProcess;
import com.example.test.model.imgdown.AsyncDownHeadImageTask;
import com.example.test.model.imgdown.AsyncDownStatusImageTask;
import com.example.test.model.json_analyzer.HashDataProcessor;
import com.example.test.model.json_analyzer.SinaJsonAnalyzer;
import com.example.test.model.social_api.NetAPI;
import com.example.test.model.social_api.QQAPI;
import com.example.test.model.social_api.SinaAPI;
import com.example.test.model.social_api.SohuWeiboAPI;
import com.netease.microblog.http.blogapi.NeteaseApi;
import com.tencent.weibo.sdk.android.model.GlobalVar;

import android.R.drawable;
import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextPaint;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class WeiBoDetailActivity extends Activity {

	String idWeiBo;
	 HashMap<String, List<byte[]>> mapImgList=new HashMap<String, List<byte[]>>();
	 HashMap<String, List<String>> mapTypeList=new HashMap<String, List<String>>();
	List<HashMap<String, String>> lArrData;
	List<HashMap<String, String>> lCommentData;
	List<HashMap<String, String>> lRepostData;
	LinearLayout llComments;
	LinearLayout llReposts;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_weibodetail);
		idWeiBo = getIntent().getStringExtra("weiboID");
		llComments =(LinearLayout)findViewById(R.id.llComment);
		llReposts =(LinearLayout)findViewById(R.id.llRepost);
		llReposts.setVisibility(View.VISIBLE);
    	llComments.setVisibility(View.INVISIBLE);
		if(getIntent().getStringExtra("resource").equals("sina"))
		{
		SinaAPI.getWeiBo(handler, idWeiBo);
		}
		else if(getIntent().getStringExtra("resource").equals("QQ"))
		{
		QQAPI.getOneWeibo(this, idWeiBo, handler);
		}
		else if(getIntent().getStringExtra("resource").equals("netease"))
		{
		NetAPI.getOneWeibo(idWeiBo, handler);
		}
		else if(getIntent().getStringExtra("resource").equals("sohu"))
		{
		SohuWeiboAPI.getOneWeibo(idWeiBo, handler);
		}
	}
    public Handler handler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Constants.MSG_GETONEWEIBO_SUCCESS:
				lArrData=(List<HashMap<String,String>>)msg.obj;
				setUI();
				break;
			case Constants.MSG_GETCOMMENTLIST_SUCCESS:
				lCommentData=(List<HashMap<String,String>>)msg.obj;
				setCommentList();
				break;
			case Constants.MSG_GETREPOSTLIST_SUCCESS:
				lRepostData=(List<HashMap<String,String>>)msg.obj;
				setRepostList();
				break;
			case Constants.MSG_DOWNIMG_SUCCESS:
				ImageView ivUserHead =(ImageView)findViewById(R.id.ivuserhead);
				Drawable drawable=(Drawable)((HashMap<String, Object>)msg.obj).get("img");
				ivUserHead.setImageDrawable(drawable);
				break;
			case Constants.MSG_DOWNSTATUSIMG_SUCCESS:
				{
					HashMap<String, Object> map=(HashMap<String, Object>)msg.obj;
					String id=(String)map.get("id");
					String [] temp=id.split("_");
					mapImgList.get(temp[0]+"_"+temp[1]).set(Integer.parseInt(temp[2]), (byte[])map.get("img"));
					mapTypeList.get(temp[0]+"_"+temp[1]).set(Integer.parseInt(temp[2]), (String)map.get("type"));
					setStatusImg();
					break;
				}
			default:
				break;
			}
		}
    	
    };
    private void setCommentList()
    {
    	for (HashMap<String, String> map : lCommentData) {
    		View convertView=LayoutInflater.from(WeiBoDetailActivity.this).inflate
				    (R.layout.comment_repost_item,null);
    		((TextView)convertView.findViewById(R.id.tvuser)).setText(
						map.get("userscreen_name")+":");
				StatusTextProcess.setText(this, ((TextView)convertView.findViewById(R.id.tvtext)), map.get("text"), null, map.get("resource"));
				((TextView)convertView.findViewById(R.id.tvtime)).setText(CommonFunc.FromSinaDateTo(map.get("created_at"), "MM-dd HH:mm"));
			llComments.addView(convertView);
		}
    }
    
    private void startDownStatusImg(List<HashMap<String,String>> tempList)
	 {
		 int i=0;
			for (HashMap<String, String> hashMap : tempList) {
				if(tempList.get(i).get("resource").equals("netease"))
				{
					System.out.println("");
				}
				String id;
				String retid="";
				String images;
				String retimages="";
				id=tempList.get(i).get("resource")+"_"+tempList.get(i).get("id");
				images=hashMap.get("images");
				if(hashMap.get("retweeted_statusid")!=null)
				{
				retid=tempList.get(i).get("resource")+"_"+tempList.get(i).get("retweeted_statusid");
				retimages=hashMap.get("retweeted_statusimages");
				}
				List<byte[]> imgList=new LinkedList<byte[]>();
				List<String> typeList=new LinkedList<String>();
				if(!images.equals("")&&mapImgList.get(id)==null)
				{
					String []arrUrl=images.split(",");
					
					int j=0;
					for (String string : arrUrl) {
						byte[] drawable=null;
						imgList.add(drawable);
						typeList.add("jpg");
			Thread thread=new Thread(new AsyncDownStatusImageTask(handler, id+"_"+j,string));
			thread.start();
						j++;
					}
					
					
				}
				if(mapImgList.get(id)==null)
				{
				mapImgList.put(id, imgList);
				mapTypeList.put(id, typeList);
				}
				if(mapImgList.get(retid)==null)
				{
				List<byte[]> imgRetList=new LinkedList<byte[]>();
				List<String> typeRetList=new LinkedList<String>();
				if(!retimages.equals("")&&mapImgList.get(retid)==null)
				{
					String []arrUrl=retimages.split(",");
					
					int j=0;
					for (String string : arrUrl) {
						byte[] drawable=null;
						imgRetList.add(drawable);
						typeRetList.add("jpg");
			Thread thread=new Thread(new AsyncDownStatusImageTask(handler, retid+"_"+j,string));
			thread.start();
						j++;
					}
					

					mapImgList.put(retid, imgRetList);
					mapTypeList.put(retid, typeRetList);
				}
				}
				i++;
			}
	 }
	
    
    private void setRepostList()
    {
    	for (HashMap<String, String> map : lRepostData) {
    		View convertView=LayoutInflater.from(WeiBoDetailActivity.this).inflate
				    (R.layout.comment_repost_item,null);
				((TextView)convertView.findViewById(R.id.tvuser)).setText(
						map.get("userscreen_name")+":");
				StatusTextProcess.setText(this, ((TextView)convertView.findViewById(R.id.tvtext)), map.get("text"), null, map.get("resource"));
				((TextView)convertView.findViewById(R.id.tvtime)).setText(CommonFunc.FromSinaDateTo(map.get("created_at"), "MM-dd HH:mm"));
			llReposts.addView(convertView);
		}
    	
    }
    
    private void setStatusImg()
    {
    	String tid=((String)lArrData.get(0).get("resource"))+"_"+((String)lArrData.get(0).get("id"));
	    List<byte[]> tempList = mapImgList.get(tid);
	    List<String> tempTypeList = mapTypeList.get(tid);
		TableLayout tableLayout =(TableLayout)findViewById(R.id.tlPics);
		tableLayout.removeAllViews();
	    if(tempList.size()>0)
		{
	    	WindowManager wm = ((Activity)this).getWindowManager();
	    	int width = wm.getDefaultDisplay().getWidth();
	    	
			TableRow row=null;
	    for(int i=0;i<tempList.size();i++)
		{
	    
	    		row=new TableRow(this);
	    		if(!tempTypeList.get(i).equals("gif"))
	    		{
			ImageView view = new ImageView(this);
			if(tempList.get(i)!=null)
			{
				row.setGravity(Gravity.CENTER);
			Drawable zoomDrawable=ModifyDrawableScale.zoomDrawable(FormatTools.getInstance().Bytes2Drawable(tempList.get(i)), ModifyDrawableScale.dip2px(this, width-20));
			view.setImageDrawable(zoomDrawable);
			}
			row.addView(view);
	    		}
	    		else
	    		{
	    			GifView view = new GifView(this);
	    			if(tempList.get(i)!=null)
	    			{
	    				row.setGravity(Gravity.CENTER);
	    				view.setGifImage(tempList.get(i));
	    				//view.setShowDimension(ModifyDrawableScale.dip2px(this, width-20),50);
	    			    
	    			}
	    			row.addView(view);
	    		}
			tableLayout.addView(row);
		}
		}
	    String retid=lArrData.get(0).get("resource")+"_"+lArrData.get(0).get("retweeted_statusid");
	    List<byte[]> tempRetList = mapImgList.get(retid);
	    List<String> tempTypeRetList = mapTypeList.get(retid);
	    TableLayout tableRetLayout =(TableLayout)findViewById(R.id.tlretPics);
	    tableRetLayout.removeAllViews();
	    if(tempRetList!=null&&tempRetList.size()>0)
		{
	    	WindowManager wm = ((Activity)this).getWindowManager();
	    	int width = wm.getDefaultDisplay().getWidth();
	    	
			TableRow row=null;
	    for(int i=0;i<tempRetList.size();i++)
		{
	    	row=new TableRow(this);
	    	if(!tempTypeRetList.get(i).equals("gif"))
	    	{
			ImageView view = new ImageView(this);
			if(tempRetList.get(i)!=null)
			{
				row.setGravity(Gravity.CENTER);
			Drawable zoomDrawable=ModifyDrawableScale.zoomDrawable(FormatTools.getInstance().Bytes2Drawable(tempRetList.get(i)), ModifyDrawableScale.dip2px(this, width-20));
			view.setImageDrawable(zoomDrawable);
			}
			row.addView(view);
	    	}
	    	else
	    	{
	    		GifView view = new GifView(this);
				if(tempRetList.get(i)!=null)
				{
					row.setGravity(Gravity.CENTER);
				    view.setGifImage(tempRetList.get(i));
					view.setShowDimension(ModifyDrawableScale.dip2px(this, width-20),300);
				
				}
				row.addView(view);
	    	}
			tableRetLayout.addView(row);
		}
		}
	    
	   
	    
	    
    }
    
    
    
	private void setUI()
	{
		HashMap<String, String> map =lArrData.get(0);
		Thread thread =new Thread( new AsyncDownHeadImageTask(handler, 0, map.get("userprofile_image_url")));
		thread.start();
		
		
		HashDataProcessor.timelineDataProcess(lArrData);
		startDownStatusImg(lArrData);
		TextView tvusername=(TextView)findViewById(R.id.tvusername);
		TextView tvsource=(TextView)findViewById(R.id.tvsource);
		TextView tvretstatustext=(TextView)findViewById(R.id.tvretstatustext);
		TextView tvcretime=(TextView)findViewById(R.id.tvcretime);
		TextView tvstatustext=(TextView)findViewById(R.id.tvstatustext);
		final TextView tvstatusreposts=(TextView)findViewById(R.id.tvstatusreposts);
		final TextView tvstatuscomment=(TextView)findViewById(R.id.tvstatuscomment);
		final TextView tvstatusattitude=(TextView)findViewById(R.id.tvstatusattitude);
		tvusername.setText(map.get("userscreen_name"));
		tvsource.setText(map.get("source"));
	    tvcretime.setText(map.get("created_at"));
	    tvstatusreposts.setText(map.get("reposts_count"));
	    tvstatuscomment.setText(map.get("comments_count"));
	    tvstatusattitude.setText(map.get("attitudes_count"));
	    StatusTextProcess.setText(this,tvstatustext,map.get("text"),map.get("id"),map.get("resource"));
	    if(map.get("retweeted_statustext")!=null)
		{
			tvretstatustext.setVisibility(View.VISIBLE);
			String content =map.get("retweeted_statususerscreen_name")+":"+map.get("retweeted_statustext");
			StatusTextProcess.setText(this,tvretstatustext,"@"+map.get("retweeted_statususerscreen_name")+" :"+map.get("retweeted_statustext"),map.get("retweeted_statusid"),map.get("resource"));
			
		}
		else
		{
			tvretstatustext.setVisibility(View.GONE);
		}
	    tvstatuscomment.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				LinearLayout lvComments =(LinearLayout)findViewById(R.id.llComment);
		    	LinearLayout lvReposts =(LinearLayout)findViewById(R.id.llRepost);
		    	lvReposts.setVisibility(View.INVISIBLE);
		    	lvComments.setVisibility(View.VISIBLE);
			}
		});
	    tvstatusreposts.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				LinearLayout lvComments =(LinearLayout)findViewById(R.id.llComment);
		    	LinearLayout lvReposts =(LinearLayout)findViewById(R.id.llRepost);
		    	lvReposts.setVisibility(View.VISIBLE);
		    	lvComments.setVisibility(View.INVISIBLE);
			}
		});
     }
	}